<template>
  <div class="user-management-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
          <el-button type="primary" @click="handleCreate">新增用户</el-button>
        </div>
      </template>

      <!-- Search Form -->
      <el-form :model="searchForm" inline>
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="searchForm.email" placeholder="请输入邮箱" clearable />
        </el-form-item>
        <el-form-item label="会员类型">
          <el-select v-model="searchForm.membershipType" placeholder="请选择会员类型" clearable>
            <el-option label="普通用户" value="NORMAL" />
            <el-option label="VIP用户" value="VIP" />
            <el-option label="SVIP用户" value="SVIP" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- User Table -->
      <el-table
          :data="userList"
          v-loading="loading"
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="userId" label="用户ID" width="80" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="nickname" label="昵称" width="120" />
        <el-table-column prop="email" label="邮箱" width="200" />
        <el-table-column label="头像" width="100">
          <template #default="{ row }">
            <el-image
                style="width: 50px; height: 50px"
                :src="row.avatarUrl"
                :preview-src-list="[row.avatarUrl]"
                fit="cover"
                hide-on-click-modal
            />
          </template>
        </el-table-column>
        <el-table-column label="会员类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getMembershipTypeColor(row.membershipType)">
              {{ getMembershipTypeName(row.membershipType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="currentLevel" label="等级" width="80" />
        <el-table-column label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastLoginTime" label="最后登录时间" width="180">
          <template #default="{ row }">
            {{ row.lastLoginTime || '从未登录' }}
          </template>
        </el-table-column>
        <el-table-column prop="loginIp" label="登录IP" width="150">
          <template #default="{ row }">
            {{ row.loginIp || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row.userId)">删除</el-button>
            <el-button size="small" type="warning" @click="resetPassword(row.userId)">重置密码</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- Pagination -->
      <div class="pagination-container">
        <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.size"
            :total="pagination.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>

      <!-- Batch Actions -->
      <div class="batch-actions" v-if="selectedUsers.length > 0">
        <el-button type="danger" @click="batchDelete">批量删除</el-button>
        <span class="selected-count">已选择 {{ selectedUsers.length }} 项</span>
      </div>
    </el-card>

    <!-- User Form Dialog -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="50%"
        :close-on-click-modal="false"
        @closed="resetForm"
    >
      <el-form
          ref="userFormRef"
          :model="userForm"
          :rules="userRules"
          label-width="100px"
          label-position="right"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="userForm.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="头像URL" prop="avatarUrl">
          <el-input v-model="userForm.avatarUrl" placeholder="请输入头像URL" />
        </el-form-item>
        <el-form-item label="会员类型" prop="membershipType">
          <el-select v-model="userForm.membershipType" placeholder="请选择会员类型">
            <el-option label="普通用户" value="NORMAL" />
            <el-option label="VIP用户" value="VIP" />
            <el-option label="SVIP用户" value="SVIP" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
              v-model="userForm.status"
              :active-value="1"
              :inactive-value="0"
              active-text="启用"
              inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '../services/api'

// 数据状态
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('新增用户')
const userFormRef = ref(null)
const selectedUsers = ref([])

// 分页数据
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

// 搜索表单
const searchForm = reactive({
  username: '',
  email: '',
  membershipType: '',
  status: ''
})

// 用户表单
const userForm = reactive({
  userId: null,
  username: '',
  email: '',
  nickname: '',
  avatarUrl: '',
  membershipType: 'NORMAL',
  status: 1
})

// 表单验证规则
const userRules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ]
})

// 用户列表数据
const userList = ref([])

// 生命周期钩子
onMounted(() => {
  fetchUserList()
})

// 获取用户列表
const fetchUserList = async () => {
  try {
    loading.value = true
    const params = {
      ...searchForm,
      page: pagination.page,
      size: pagination.size
    }

    const response = await api.userManageApi.getUserList(params)

    if (response.code === 200) {
      // 处理后端返回的数据结构
      const data = response.data
      userList.value = data.records || data.list || []

      // 处理分页信息
      pagination.total = data.total || 0

      // 如果后端没有返回分页信息，使用records数组长度
      if (!data.total && data.records) {
        pagination.total = data.records.length
      }
    } else {
      ElMessage.error(response.message || '获取用户列表失败')
    }
  } catch (error) {
    console.error('获取用户列表出错:', error)
    ElMessage.error('获取用户列表出错')
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  pagination.page = 1
  fetchUserList()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.size = size
  fetchUserList()
}

// 当前页变化
const handleCurrentChange = (page) => {
  pagination.page = page
  fetchUserList()
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedUsers.value = selection.map(item => item.userId)
}

// 打开创建对话框
const handleCreate = () => {
  dialogTitle.value = '新增用户'
  dialogVisible.value = true
}

// 打开编辑对话框
const handleEdit = (row) => {
  dialogTitle.value = '编辑用户'
  Object.keys(userForm).forEach(key => {
    if (row[key] !== undefined) {
      userForm[key] = row[key]
    }
  })
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  try {
    await userFormRef.value.validate()

    const formData = { ...userForm }
    // 移除userId如果是新增
    if (!formData.userId) {
      delete formData.userId
    }

    let response
    if (formData.userId) {
      // 更新用户 (这里可能需要根据实际API调整)
      ElMessage.info('用户更新功能待实现')
      return
    } else {
      // 创建用户 (这里可能需要根据实际API调整)
      ElMessage.info('用户创建功能待实现')
      return
    }

    if (response.code === 200) {
      ElMessage.success(formData.userId ? '更新用户成功' : '创建用户成功')
      dialogVisible.value = false
      fetchUserList()
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('表单提交出错:', error)
    if (error instanceof Error) {
      ElMessage.error(error.message || '表单验证失败')
    }
  }
}

// 删除用户
const handleDelete = (userId) => {
  ElMessageBox.confirm('确认删除该用户吗?', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await api.userManageApi.deleteUser(userId)
      if (response.code === 200) {
        ElMessage.success('删除用户成功')
        fetchUserList()
      } else {
        ElMessage.error(response.message || '删除用户失败')
      }
    } catch (error) {
      console.error('删除用户出错:', error)
      ElMessage.error('删除用户出错')
    }
  }).catch(() => {
    // 用户取消
  })
}

// 重置密码
const resetPassword = (userId) => {
  ElMessageBox.confirm('确认重置该用户密码吗?', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await api.userManageApi.resetUserPassword(userId, '123456')
      if (response.code === 200) {
        ElMessage.success('重置密码成功，新密码为：123456')
      } else {
        ElMessage.error(response.message || '重置密码失败')
      }
    } catch (error) {
      console.error('重置密码出错:', error)
      ElMessage.error('重置密码出错')
    }
  }).catch(() => {
    // 用户取消
  })
}

// 批量删除
const batchDelete = () => {
  if (selectedUsers.value.length === 0) {
    ElMessage.warning('请至少选择一项')
    return
  }

  ElMessageBox.confirm(`确认删除选中的 ${selectedUsers.value.length} 个用户吗?`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await api.userManageApi.batchDeleteUsers(selectedUsers.value)
      if (response.code === 200) {
        ElMessage.success('批量删除成功')
        selectedUsers.value = []
        fetchUserList()
      } else {
        ElMessage.error(response.message || '批量删除失败')
      }
    } catch (error) {
      console.error('批量删除出错:', error)
      ElMessage.error('批量删除出错')
    }
  }).catch(() => {
    // 用户取消
  })
}

// 重置表单
const resetForm = () => {
  userFormRef.value?.resetFields()
  Object.keys(userForm).forEach(key => {
    if (key === 'status') {
      userForm[key] = 1
    } else if (key === 'membershipType') {
      userForm[key] = 'NORMAL'
    } else {
      userForm[key] = ''
    }
  })
  userForm.userId = null
}

// 获取会员类型名称
const getMembershipTypeName = (type) => {
  const typeMap = {
    'NORMAL': '普通用户',
    'VIP': 'VIP用户',
    'SVIP': 'SVIP用户'
  }
  return typeMap[type] || type
}

// 获取会员类型颜色
const getMembershipTypeColor = (type) => {
  const colorMap = {
    'NORMAL': '',
    'VIP': 'warning',
    'SVIP': 'danger'
  }
  return colorMap[type] || ''
}
</script>

<style scoped>
.user-management-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.batch-actions {
  margin-top: 20px;
  display: flex;
  align-items: center;
}

.selected-count {
  margin-left: 15px;
  color: #666;
  font-size: 14px;
}
</style>
